<template>
  <div>
    <!-- 表单 -->
    <el-form :label-position="labelPosition" size="small" :model="query" :inline="true">
      <el-form-item label="名称" style="font-weight:bold;">
        <el-input v-model="query.name" placeholder="" style="width:180px;" clearable></el-input>
      </el-form-item>
      <el-form-item label="生产商家" style="font-weight:bold;">
        <el-input v-model="query.manufacturer" placeholder="" style="width:180px;" clearable></el-input>
      </el-form-item>
      <el-button size="small" class="search_button" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      <el-button size="small" class="reset_button" icon="el-icon-refresh" @click="reset">重置</el-button>
    </el-form>
    <!-- 表单 -->
    <div style="display:flex;">
      <el-button style="margin-right:10px;" size="small" type="primary" icon="el-icon-plus"
        @click="showAdd">新增</el-button>
      <el-button style="margin-right:10px;" size="small" type="success" icon="el-icon-download" @click="downLoad"
        plain>下载维修材料模板</el-button>
      <el-upload action="#" :before-upload="beforeUpload" ref="newuploadin" :show-file-list="false"
        :http-request="uploadHttpRequest" :limit="3" :file-list="fileList">
        <el-button size="small" type="primary" plain icon="el-icon-upload2">导入维修材料</el-button>
      </el-upload>
    </div>
    <el-divider></el-divider>

    <!-- 表格 -->
    <el-table size="medium" ref="multipleTable" :data="tableData" border style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column prop="name" label="名称" align="center"></el-table-column>
      <el-table-column prop="unit" label="单位" align="center"></el-table-column>
      <el-table-column prop="price" label="单价" align="center"></el-table-column>
      <el-table-column prop="specifications" label="规格" align="center"></el-table-column>
      <el-table-column prop="manufacturer" label="生产商家" align="center"></el-table-column>
      <el-table-column prop="warrantyTime" label="质保期限" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="small" type="text" icon="el-icon-refresh" @click="showChange(scope.row)">修改</el-button>
        </template>
      </el-table-column>

    </el-table>
    <!-- 表格 -->

    <el-pagination class="pagination" background layout="total, sizes, prev, pager, next, jumper" :total="total"
      :page-size="10" :page-sizes="[10, 20, 30, 40]" @current-change="handleCurrentChange"
      @size-change="handleSizeChange"></el-pagination>


    <el-dialog :title="title" :visible.sync="dialog" center width="40%">
      <el-form :label-position="labelPosition" size="small" :model="form" label-width="100px">
        <el-form-item label="名称" style="font-weight:bold;">
          <el-input v-model="form.name" placeholder="" style="width:80%" clearable></el-input>
        </el-form-item>
        <el-form-item label="单位" style="font-weight:bold;">
          <el-input v-model="form.unit" placeholder="" style="width:80%" clearable></el-input>
        </el-form-item>
        <el-form-item label="单价" style="font-weight:bold;">
          <!-- <el-input v-model="form.price" placeholder="" style="width:80%" clearable></el-input> -->
          <el-input-number v-model="form.price" style="width:80%"></el-input-number>
        </el-form-item>
        <el-form-item label="规格" style="font-weight:bold;">
          <el-input v-model="form.specifications" placeholder="" style="width:80%" clearable></el-input>
        </el-form-item>
        <el-form-item label="生产商家" style="font-weight:bold;">
          <el-input v-model="form.manufacturer" placeholder="" style="width:80%" clearable></el-input>
        </el-form-item>
        <el-form-item label="质保期限" style="font-weight:bold;">
          <el-date-picker v-model="form.warrantyTime" type="date" placeholder="选择日期" format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd" style="width:80%" clearable>
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog = false">取 消</el-button>
        <el-button type="primary" @click="comfirm">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { getList, addMaterial, updateMaterial, downLoad, uploadMaterial } from "_api/MaintainView/MaterialManage/index.js"

export default {
  data() {
    return {
      dialog: false,
      title: "",
      labelPosition: "right",
      query: {
        current: 0,
        pageSize: 10,
        name: "",
        manufacturer: ""
      },
      form: {
        name: "",
        unit: "",
        price: '',
        specifications: "",
        manufacturer: '',
        warrantyTime: ''
      },
      tableData: [],
      total: 0,
      clientRole: '',
      fileList: [],
      timeNow: ''
    }
  },
  methods: {
    getCurrentTime() {
      //获取当前时间并打印
      var _this = this;
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth() + 1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes();
      let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds();
      _this.gettime = yy + '/' + mm + '/' + dd + ' ' + hh + ':' + mf + ':' + ss;
      console.log(_this.gettime)
      this.timeNow = _this.gettime
    },
    // 下载模板
    downLoad() {
      this.$confirm('是否确认下载?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        downLoad().then(res => {
          const link = document.createElement('a')  //创建a标签
          const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' }) //设置文件流
          link.style.display = 'none'// 设置连接
          link.href = URL.createObjectURL(blob)  //将文件流转化为blob地址
          this.getCurrentTime()
          link.download = '维修材料模板_' + this.timeNow
          document.body.appendChild(link) // 模拟点击事件
          link.click()  //设置点击事件
          this.$message.success('下载成功！')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    beforeUpload(file) {
      // 校验
      let legalName = ["xlsx", "xls"];
      // 拿到后缀名
      let name = file.name.substring(
        file.name.lastIndexOf(".") + 1,
        file.name.length
      );
      if (legalName.includes(name)) {
      } else {
        this.$message.info("文件格式不对,仅限xls和xlsx");
        return false;
      }
    },
    // 导入维修单信息
    uploadHttpRequest(data) {
      let fd = new FormData()
      fd.append('file', data.file)
      const loading = this.$loading({
        lock: true,
        text: '数据导入中,请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      uploadMaterial(fd).then(res => {
        if (res.data.success == true) {
          loading.close();
          this.$message.success("导入成功！")
          this.reset()
        } else {
          loading.close();
          this.$message({
            message: res.data.message,
            duration: 3000
          })
        }
      }).catch(error => {
        loading.close();
        if (error.response.status != 200) {
          this.$message.info(error.response.data.message)
        }
      })
    },
    resetForm() {
      this.form = {
        name: "",
        unit: "",
        price: '',
        specifications: "",
        manufacturer: '',
        warrantyTime: ''
      }
    },
    showAdd() {
      this.resetForm()
      this.dialog = true
      this.title = "新增维修材料"
    },
    showChange(e) {
      this.resetForm()
      this.dialog = true
      this.title = "修改维修材料"
      this.form = e
    },
    comfirm() {
      if (this.title == "新增维修材料") {
        addMaterial(this.form).then(res => {
          if (res.data.success == true) {
            this.dialog = false
            this.$message({
              message: '添加成功!',
              duration: 1000,
              type: 'success',
              onClose: () => {
                this.reset()
              }
            })
          } else {
            this.$message.info(res.data.message)
          }
        }).catch(error => {
          if (error.response.status != 200) {
            this.$message.info(error.response.data.message)
          }
        })
      }
      if (this.title == "修改维修材料") {
        updateMaterial(this.form).then(res => {
          if (res.data.success == true) {
            this.dialog = false
            this.$message({
              message: '修改成功!',
              duration: 1000,
              type: 'success',
              onClose: () => {
                this.reset()
              }
            })
          } else {
            this.$message.info(res.data.message)
          }
        }).catch(error => {
          if (error.response.status != 200) {
            this.$message.info(error.response.data.message)
          }
        })
      }
    },
    handleSelectionChange() {

    },
    //重置
    reset() {
      this.query = {
        current: 0,
        pageSize: 10,
        name: "",
        manufacturer: ""
      }
      this.getDataList()
    },
    handleCurrentChange(e) {
      //当前页
      this.query.current = e
      this.getDataList()
    },
    handleSizeChange(e) {
      this.query.pageSize = e
      this.getDataList()
    },
    // 查询按钮
    search() {
      this.query.current = 0
      this.getDataList()
    },
    //列表查询
    getDataList() {
      getList(this.query).then(res => {
        if (res.data.success == true) {
          res.data.data.list.forEach(item => {
            item.warrantyTime.forEach(Item => {
              if (Item < 10) {
                Item = '0' + Item
              }
            })
            item.warrantyTime = item.warrantyTime.join('-')
          })
          this.tableData = res.data.data.list
          this.total = res.data.data.total
        } else {
          this.tableData = res.data.data
          this.total = ""
          this.$message.info(res.data.message)
        }
      })
    },


  },
  created() {
    this.getDataList()
  },
};
</script>
<style lang="scss" scoped>
.reset_button {
  margin-left: 10px;
}

.search_button {
  margin-left: 70px;
}

// .delete_button{
//   margin-left: 10px;
// }
.dialogbutton {
  margin-right: 40%;
}

.pagination {
  float: right;
  margin-top: 10px;
}
</style>
